#include "emb.h"

uint8_t mutex[MUTEX_MAX_NUM];

uint8_t mutex_take(mutex_typeDef type)
{
	if(mutex[type])
	{
		mutex[type] = 0;
		return 0;
	}
	else
	{
		return 1;
	}
}

uint8_t mutex_realse(mutex_typeDef type)
{
	if(!mutex[type])
	{
		mutex[type] = 1;
		return 0;
	}
	else
	{
		return 1;
	}
}

uint8_t mutex_stat(mutex_typeDef type)
{
	return mutex[type];
}

void laser_on(void)
{
	mutex_take(laser);
	GPIOPinWrite(laser_light_1.port, laser_light_1.pin, laser_light_1.pin);
}

void laser_off(void)
{
	GPIOPinWrite(laser_light_1.port, laser_light_1.pin, 0);
	mutex_realse(laser);
}

void beep_on(void)
{
	mutex_take(beep);
	GPIOPinWrite(buzzer.port, buzzer.pin, buzzer.pin);
}

void beep_off(void)
{
	GPIOPinWrite(buzzer.port, buzzer.pin, 0);
	mutex_realse(beep);
}


#define INT_PERIORD 5
typedef struct IO_period
{
	int cnt;
	int hight_ms;
	int low_ms;	
	
	int cnt_time;
	int state;
	
	int busy;
}IO_period;

IO_period beep_period;
IO_period laser_period;
//IO_period laser2_period;


uint8_t is_busy_beep(void)
{
	return beep_period.busy;
}

uint8_t is_laser_beep(void)
{
	return laser_period.busy;
}


void start_been(int cnt,int hight_ms,int low_ms)
{
	beep_period.cnt = cnt;
	beep_period.hight_ms = hight_ms;	
	beep_period.low_ms = low_ms;	

	beep_period.cnt_time = 0;
	beep_period.state = 0;
	beep_period.busy = 1;
	beep_on();
}

void start_laser(int cnt,int hight_ms,int low_ms)
{
	laser_period.cnt = cnt;
	laser_period.hight_ms = hight_ms;	
	laser_period.low_ms = low_ms;	

	laser_period.cnt_time = 0;
	laser_period.state = 0;
	laser_period.busy = 1;	
	laser_on();	
}

void IO_Remind_Run_CallBack(void)
{
	switch(beep_period.state)
	{
		case 0:
		{
			beep_period.cnt_time += INT_PERIORD;			
			if(beep_period.cnt_time >= beep_period.hight_ms)
			{
				beep_off();
				beep_period.state = 1;
				beep_period.cnt_time = 0;
			}
		}
		break;
		case 1:
		{
			beep_period.cnt_time += INT_PERIORD;			
			if(beep_period.cnt_time >= beep_period.low_ms)
			{
				beep_period.cnt_time = 0;
				beep_period.cnt--;
				if(beep_period.cnt == 0)
				{
					beep_period.state = 2;	
					beep_period.busy = 0;						
				}
				else
				{	
					beep_on();
					beep_period.state = 0;	
				}
			}			
		}
		break;
		default:
			break;		
	}
	
	switch(laser_period.state)
	{
		case 0:
		{
			laser_period.cnt_time += INT_PERIORD;			
			if(laser_period.cnt_time >= laser_period.hight_ms)
			{
				laser_off();
				laser_period.state = 1;
				laser_period.cnt_time = 0;
			}
		}
		break;
		case 1:
		{
			laser_period.cnt_time += INT_PERIORD;			
			if(laser_period.cnt_time >= laser_period.low_ms)
			{
				laser_period.cnt_time = 0;
				laser_period.cnt--;
				if(laser_period.cnt == 0)
				{
					laser_period.state = 2;		
					laser_period.busy = 0;						
				}
				else
				{	
					laser_on();
					laser_period.state = 0;	
				}
			}			
		}
		break;
		default:
			break;		
	}
}













